package io.github.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import io.github.entity.SysAreaEntity;
import io.github.entity.SysPageEntity;
import io.github.entity.SysUserEntity;
import io.github.service.SysAreaServive;
import io.github.service.SysUserRoleService;
import io.github.service.SysUserService;
import io.github.util.PageUtils;
import io.github.util.R;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 系统用户
 */
@Controller
@RequestMapping("/admin/sys/user")
public class SysUserController extends AbstractController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysAreaServive sysAreaServive;
    @Resource
    private SysUserRoleService sysUserRoleService;

    /**
     * 所有用户列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public R list(@RequestBody SysPageEntity enti) {
        logger.info("获取所有用户");

        Integer offset = enti.getOffset();
        Integer limit = enti.getLimit();
        // 排序逻辑
        Boolean flag = null;
        if (StringUtils.isNoneBlank(enti.getOrder())) {
            if ("asc".equalsIgnoreCase(enti.getOrder())) {
                flag = true;
            } else {
                flag = false;
            }
        }
        //声明一个新的用户集合
        List<SysUserEntity> newList = new ArrayList<SysUserEntity>();

        Page<SysUserEntity> adminList = sysUserService.queryListByPage(offset, limit, flag);
        //获取用户集合
        List<SysUserEntity> list = adminList.getRecords();

        for (int i = 0; i < list.size(); i++) {
            //声明新的实体类
            SysUserEntity modelEntity = new SysUserEntity();
            //获取地区ID字符串
            String areaid = list.get(i).getAreaid();
            //字符串转数组
            String[] split = areaid.split(",");

            List<String> nameList = new ArrayList<String>();

            for (String aId : split) {
                //通过地区ID获取地区属性
                SysAreaEntity sysAreaEntity = sysAreaServive.selectById(aId);
                nameList.add(sysAreaEntity.getName());
            }

            modelEntity.setNameList(nameList);
            modelEntity.setUsername(list.get(i).getUsername());
            modelEntity.setUserId(list.get(i).getUserId());
            modelEntity.setAreaid(areaid);
            modelEntity.setEmail(list.get(i).getEmail());
            modelEntity.setMobile(list.get(i).getMobile());
            modelEntity.setNickname(list.get(i).getNickname());

            newList.add(modelEntity);

        }

        PageUtils pageUtil = new PageUtils(newList, adminList.getTotal(), adminList.getSize(),
                adminList.getCurrent());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 根据昵称查询
     */
    @RequestMapping("/nickname")
    @ResponseBody
    public R nickName(@RequestBody JSONObject jsonObject) {
        logger.info("根据昵称查询");
        Integer offset = jsonObject.getInteger("offset");
        Integer limit = jsonObject.getInteger("limit");
        String nickname = jsonObject.getString("nickname");
        Page<SysUserEntity> adminList = sysUserService.queryListByPage(offset, limit, nickname);
        List<SysUserEntity> recordList = adminList.getRecords();

        System.out.println(">>>>>size:" + recordList.size());

        for (int i = 0; i < recordList.size(); i++) {
            System.out.println(recordList.get(i).toString());
            String areaid = recordList.get(i).getAreaid();
            String[] split = areaid.split(",");
            List<String> nameList = new ArrayList<String>();
            //设置地区名字
            for (int j = 0; j < split.length; j++) {
                Integer aid = Integer.valueOf(split[j]);
                nameList.add(sysAreaServive.selectById(aid).getName());
            }
            recordList.get(i).setNameList(nameList);
            List<Long> list = sysUserRoleService.queryRoleIdList(recordList.get(i).getUserId());
            recordList.get(i).setRoleIdList(list);
            List<String> list1 = sysUserRoleService.queryRoleNames(recordList.get(i).getUserId());
            recordList.get(i).setRoleNameList(list1);
        }

        PageUtils pageUtil = new PageUtils(recordList, adminList.getTotal(), adminList.getSize(),
                adminList.getCurrent());
        return R.ok().put("page", pageUtil);

    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    @ResponseBody
    public R info() {
        logger.info("获取登录用户信息接口");
        return R.ok().put("user", getAdmin());
    }

    /**
     * 用户信息
     */
    @RequestMapping("/info/{userId}")
    @ResponseBody
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.selectById(userId);

        // 获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }

    /**
     * 增加用户
     */
    @RequestMapping("/add")
    @ResponseBody
    public R save(@RequestBody JSONObject jsonObject) {
        logger.info("增加用户接口");

        SysUserEntity entity = new SysUserEntity();
        //获取角色id
        String roleId = jsonObject.getString("roleIds");
        System.out.println(">>>>>roleIds:" + roleId);
        //分隔字符串
        String[] split = roleId.split(",");
        //声明数组 存储菜单角色id
        Long[] roles = new Long[split.length];
        //获取用户名
        String username = jsonObject.getString("username");
        //检测用户名是否存在
        SysUserEntity userEntity = sysUserService.queryByUserName(username);
        if (userEntity != null) {
            return R.error(500, "用户已存在");
        }
        for (int i = 0; i < split.length; i++) {
            System.out.println(">>>>>参数:" + split[i]);
            roles[i] = Long.valueOf(split[i]);
        }

        List<Long> roleIdList = new ArrayList<Long>();
        Collections.addAll(roleIdList, roles);

        if (roles.length < 1) {
            return R.error(500, "请为用户赋予至少一个权限");
        }

        String areaid = jsonObject.getString("areaid");

        System.out.println(">>>>>areaid:" + areaid);
        for (int i = 0; i < split.length; i++) {
            Integer id = Integer.valueOf(split[i]);
            System.out.println(">>>>>id:" + id);
        }

        //密码加密
        entity.setPassword(new Sha256Hash(jsonObject.getString("password")).toHex());
        entity.setAreaid(jsonObject.getString("areaid"));
        entity.setMobile(jsonObject.getString("mobile"));
        entity.setEmail(jsonObject.getString("email"));
        entity.setNickname(jsonObject.getString("nickname"));
        entity.setUsername(username);
        entity.setRoleIdList(roleIdList);

        System.out.println(">>>>>角色集合roleIdList:" + roleIdList);

        System.out.println(">>>>>结束时entity:" + entity.toString());
        //保存新增数据
        sysUserService.save(entity);
        return R.ok().put("user", entity);
    }

    /**
     * 修改用户
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody JSONObject jsonObject) {
        logger.info("修改用户接口");
        //获取角色id
        String roleId = jsonObject.getString("roleIds");
        String[] split = roleId.split(",");
        Long[] roles = new Long[split.length];
        for (int i = 0; i < split.length; i++) {
            System.out.println(Long.valueOf(split[i]));
            roles[i] = Long.valueOf(split[i]);
        }

        if (roles.length < 1) {
            return R.error(500, "请为用户赋予至少一个权限");
        }
        List<Long> roleIdList = new ArrayList<Long>();
        Collections.addAll(roleIdList, roles);

        //根据ID获取用户实体
        SysUserEntity userentity = sysUserService.selectById(jsonObject.getInteger("userId"));
        userentity.setMobile(jsonObject.getString("mobile"));
        userentity.setEmail(jsonObject.getString("email"));
        userentity.setAreaid(jsonObject.getString("areaid"));
        userentity.setNickname(jsonObject.getString("nickname"));
        userentity.setRoleIdList(roleIdList);
        //userentity.setLastLoginIp(userentity.getLastLoginIp());
        //user.setLastLoginTime(userentity.getLastLoginTime());
//        if (StringUtils.isBlank(user.getUsername())) {
//            return R.error("用户名不能为空");
//        }
//        if (getAdminId().equals(user.getUserId())) {
//            if (user.getStatus().equals(0)) {
//                ShiroUtils.logout(); // 退出
//            }
//        }
        sysUserService.updateUser(userentity);
        return R.ok();
    }

    /**
     * 修改用户状态
     */
    @RequestMapping("/updateStatus")
    @ResponseBody
    @RequiresPermissions("sys:user:update")
    public R updateStatus(Long userId, @RequestParam("state") Boolean status) {
        int updateStatus = sysUserService.updateStatus(userId, status ? 1 : 0);
        if (updateStatus > 0) {
            return R.ok();
        } else {
            return R.error(500, "修改失败!");
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("/delete")
    @ResponseBody
    //@RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody JSONObject jsonObject) {
        logger.info("删除用户接口");
        String idStr = jsonObject.getString("ids");
        System.out.println(">>>>>idStr:" + idStr);
        String ids = "[" + idStr + "]";
        System.out.println(">>>>>ids:" + ids);
        JSONArray jsonArray = JSONArray.parseArray(ids);
        Long[] userIds = toArrays(jsonArray);
        if (userIds.length < 1) {
            return R.error(500, "删除的用户为空");
        }
        if (ArrayUtils.contains(userIds, constant.adminId)) {
            return R.error(500, "系统管理员不能删除");
        }
        if (ArrayUtils.contains(userIds, getAdminId())) {
            return R.error(500, "当前用户不能删除");
        }
        sysUserService.deleteBatch(userIds);
        return R.ok();
    }

    /**
     * 获取用户菜单
     */
    @RequestMapping("/getmenu")
    @ResponseBody
    public R getMenu() {
        logger.info("用户菜单获取接口");
        //获取当前登录用户id
        Long userId = getAdminId();
        System.out.println(">>>>>用户userId:" + userId);
        //获取角色id
        List<Long> longList = sysUserRoleService.queryRoleIdList(36L);
        //数组格式[14, 18]
        System.out.println(">>>>>角色longList:" + longList);

        return R.ok().put("role", longList);
    }

    /**
     * 自己的个人信息
     *
     * @return
     */
    @RequestMapping("/view")
    public String view(Model model) {
        model.addAttribute("admin", getAdmin());
        return "/admin/sys/info";
    }

    /**
     * 修改头像
     *
     * @param model Model
     * @return
     */
    @RequestMapping("/avatar.html")
    public String avatar(Model model) {
        model.addAttribute("admin", getAdmin());
        return "/admin/sys/avatar";
    }

    /**
     * 更新自身信息
     *
     * @return
     */
    @RequestMapping("/updateView")
    @ResponseBody
    public R updateView(@RequestBody SysUserEntity user) {
        logger.info("修改自身信息接口");
        //获取当前登录用户信息
        SysUserEntity currentUser = getAdmin();
        currentUser.setEmail(user.getEmail());
        currentUser.setMobile(user.getMobile());
        currentUser.setNickname(user.getNickname());
        //是否修改成功
        boolean falg = sysUserService.updateById(currentUser);
        if (falg) {
            return R.ok();
        } else {
            return R.error(500, "修改失败，请联系管理员!");
        }
    }

    /**
     * 更新所有用户信息
     *
     * @return
     */
    @RequestMapping("/updateAll")
    @ResponseBody
    public R updateAll(@RequestBody SysUserEntity user) {
        logger.info("更新所有人信息接口");
        Long userId = user.getUserId();
        SysUserEntity userEntity = new SysUserEntity();

        userEntity.setNickname(user.getNickname());
        userEntity.setEmail(user.getEmail());
        userEntity.setMobile(user.getMobile());
        userEntity.setAreaid(user.getAreaid());

        sysUserService.updateEntity(userEntity, userId);
        return R.ok();
    }

    /**
     * 更新自己的头像
     *
     * @return
     */
//    @RequestMapping("/updateAvatar")
//    @ResponseBody
//    public R updateAvatar(String avatarUrl) {
//        SysUserEntity currentUser = getAdmin();
//        currentUser.setAvatarUrl(avatarUrl);
//        int updateAvatar = sysUserService.updateAvatar(currentUser);
//        if (updateAvatar > 0) {
//            return R.ok();
//        } else {
//            return R.error("修改失败!");
//        }
//    }

    /**
     * 用户修改密码
     */
    @RequestMapping("/updatePassword")
    @ResponseBody
    public R updateSelfPassword(@RequestBody JSONObject jsonObject) {
        logger.info("用户修改密码接口");
        Long userId = jsonObject.getLong("userId");
        String oldPassword = jsonObject.getString("oldPassword");
        String newPassword = jsonObject.getString("newPassword");

        if (StringUtils.isBlank(oldPassword)) {
            return R.error(500, "请输入原密码！");
        }
        if (StringUtils.isBlank(newPassword)) {
            return R.error(500, "请输入新密码！");
        }

        oldPassword = new Sha256Hash(oldPassword).toHex();
        newPassword = new Sha256Hash(newPassword).toHex();
        int count = this.sysUserService.updatePassword(userId, oldPassword, newPassword);
        if (count != 1) {
            return R.error(500, "原密码输入错误！");
        }
        return R.ok();
    }

    /**
     * 管理员修改用户密码
     */
    @RequestMapping("/updatePwd")
    @ResponseBody
    public R updatePassword(@RequestBody JSONObject jsonObject) {
        logger.info("管理员修改用户密码接口");
        Long userId = jsonObject.getLong("userId");
        String newPassword = jsonObject.getString("newPassword");

        if (StringUtils.isBlank(newPassword)) {
            return R.error(500, "请输入新密码！");
        }

        newPassword = new Sha256Hash(newPassword).toHex();
        int count = this.sysUserService.updatePwd(userId, newPassword);
        if (count != 1) {
            return R.error(500, "原密码输入错误！");
        }
        return R.ok();
    }

}
